#coding:utf-8

import Config;
import wx;
import os;
import wx.lib.rcsizer as rcs;
import wx.lib.intctrl;
import Global;
import Loading;
import string;
import ELog;
import traceback;
import array;
import time;
import numpy;  
import matplotlib;
import matplotlib.figure;
import matplotlib.backends.backend_wxagg;
import matplotlib.backends.backend_wx;

try:
    from agw import fourwaysplitter as FWS
except ImportError: # if it's not there locally, try the wxPython lib.
    try:
        import wx.lib.agw.fourwaysplitter as FWS
    except ImportError:
        exit()

#菜单ID
from AppIds import *

import SerialUtil
import wx.lib.newevent

#Frame start
SERIAL_GENIUS_FS_CHAR=0x0F;
#Slash
SERIAL_GENIUS_SL_CHAR=0x1F;


        
#接收数据
class Recv(wx.Panel):

    def __init__(self, parent):
        wx.Panel.__init__(self, parent, style=wx.BORDER_DOUBLE);
        
        ############# 状态信息 ############
        #该模块是否启用
        self.isUsing=False;

        ############# 配置信息 ############
        self.hexMode=False;
        self.dataBuffer=[];
        self.dataLength=0;
        
        
        ############# 开始布局 ###########
        gridSizer = rcs.RowColSizer();
        
        rowTotal=3;
        colTotal=4;

        #标题
        title=wx.StaticText(self, -1, u"接收");
        title.SetFont(wx.Font(8, wx.FONTFAMILY_DEFAULT, wx.FONTSTYLE_NORMAL, wx.FONTWEIGHT_BOLD ));
        gridSizer.Add(title, pos=(0,0), size=(1, colTotal), flag=wx.EXPAND|wx.ALIGN_CENTER_VERTICAL);
    
        #数据
        self.textRecvData = wx.TextCtrl(self, style=wx.TE_MULTILINE);
        self.textRecvData.SetFont(wx.Font(10, wx.FONTFAMILY_TELETYPE, wx.FONTSTYLE_NORMAL, wx.FONTWEIGHT_NORMAL ));
        self.textRecvData.SetEditable(False);
        gridSizer.Add(self.textRecvData, pos=(1,0), size=(1, colTotal), flag=wx.EXPAND|wx.ALIGN_CENTER_VERTICAL);
        
        #清空
        btn = wx.Button(self, -1, u"清空")
        self.Bind(wx.EVT_BUTTON, self.OnClearData, btn);
        gridSizer.Add(btn, pos=(2, 0), size=(1,1), flag=wx.ALIGN_CENTER_VERTICAL);

        #保存
        btn = wx.Button(self, -1, u"保存数据")
        self.Bind(wx.EVT_BUTTON, self.OnSaveData, btn);
        gridSizer.Add(btn, pos=(2, 1), size=(1,1), flag=wx.ALIGN_CENTER_VERTICAL);
        
        #显示接收到的总数据
        self.labelDataLen= wx.StaticText(self, -1, u"接收数据：0");
        gridSizer.Add(self.labelDataLen, pos=(2, 2), size=(1,1), flag=wx.ALIGN_CENTER_VERTICAL);
        
        #显示模式
        ck=wx.CheckBox(self, -1, u"十六进制显示  ");
        ck.Bind(wx.EVT_CHECKBOX, self.OnHexMode);
        gridSizer.Add(ck, pos=(2, 3), size=(1,1), flag=wx.EXPAND|wx.ALIGN_CENTER_VERTICAL);
        if Config.APP_CONFIG['module_recv']['hexMode']=='1':
            ck.SetValue(True);
            self.hexMode=True;


        
        #设置变宽信息
        gridSizer.AddGrowableCol(2);
        gridSizer.AddGrowableRow(1);


        ############# 结束布局 ###########
        self.SetSizer(gridSizer)
        self.SetAutoLayout(True)

        #更新GUI数据的线程
        (self.UpdateDataEvent, self.UPDATA_DATA_EVENT) = wx.lib.newevent.NewEvent();
        self.Bind(self.UPDATA_DATA_EVENT, self.SaveUpdateWindow)
    
    #保存数据
    def OnSaveData(self, event):
        self.textRecvData.SaveFile(time.strftime('Receive_%Y%m%d_%H_%M_%S.txt',time.localtime(time.time())));
        wx.MessageBox(u'保存成功');
        
    #新增串口数据，被串口接收所调用，这里的长度必须指定，否则字符串到\0将会终止
    def RecvData(self, data):
        self.dataBuffer.extend(data);
        self.dataLength += len(data);
        self.DataWindowAppend(data);
        self.labelDataLen.SetLabel(u"接收数据："+str(self.dataLength));  #更新接收字符总数

    #清空数据
    def OnClearData(self, event):
        del self.dataBuffer[:];
        self.dataLength=0;
        self.textRecvData.SetValue('');
        self.labelDataLen.SetLabel(u"接收数据：0");  #更新接收字符总数

    #设置十六进制显示模式
    def OnHexMode(self, event):
        Loading.Show();
        self.hexMode = event.GetEventObject().GetValue();
        self.textRecvData.SetValue('');
        self.DataWindowAppend(self.dataBuffer);
        Loading.Hide();
        if self.hexMode:
            Config.APP_CONFIG['module_recv']['hexMode']='1';
        else:
            Config.APP_CONFIG['module_recv']['hexMode']='0';
    
    #新增加数据到显示窗口
    def DataWindowAppend(self, data):
        dataStr=[];
        length=len(data);
        if self.hexMode:
            for i in range(0, length):
                dataStr.append('%02X ' % data[i]);
        else:
            for i in range(0, length):
                char =data[i];
                if char==0x0A or 32<=char<127:
                    dataStr.append(chr(char));
        wx.PostEvent(self,self.UpdateDataEvent(data=''.join(dataStr)));
        
    def SaveUpdateWindow(self, evt):
        self.textRecvData.SetInsertionPointEnd();
        self.textRecvData.WriteText(evt.data);
